package cn.kgc.service.impl;
import cn.kgc.common.md5.Md5Util;
import cn.kgc.common.redisutils.stringRedisTemplateUtil;
import cn.kgc.common.verifyutil.mobileUtil;
import cn.kgc.dao.mapper.ItripUserMapper;
import cn.kgc.dtos.Dto;
import cn.kgc.pojo.ItripUser;
import cn.kgc.service.ItripUserService;
import cn.kgc.voi.Token;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import cn.kgc.common.dtoutils.dtoUtil;
@Service
public class ItripUserServiceimpl implements ItripUserService {
    @Resource
    private ItripUserMapper itripUserMapper;
    @Resource
    private stringRedisTemplateUtil stringRedisTemplateUtil;
    @Resource
    private MailSender mailSender;
    @Resource
    private SimpleMailMessage mailMessage;

    /**
     * 登陆方法
     * @param code 用户名
     * @param pwd 密码
     * @param type 登陆类型
     * @return
     */
    @Override
    public Dto login(String code,String pwd,String type) {
        if(type.equals("UNKNOWN")){
            type="pc";
        }
        try {
            //查询是否有用户
            ItripUser itripUser= itripUserMapper.selectBycodeandpwd(code,pwd);
            if (itripUser!=null&&itripUser.getActivated()!=0){
                //生成一个token    token:来源-用户ID编码加密-用户ID-生成的时间-6位随机码
                StringBuilder sb=new StringBuilder();
                //拼凑token
                sb.append("token:"+
                        type+"-"
                        + Md5Util.encode(itripUser.getUserCode())+
                        "-"+itripUser.getId()+new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())
                        +"-"+UUID.randomUUID().toString().replace("-","").substring(6));;
                Token token=new Token();
                token.setToken(sb.toString());
                token.setGenTime(System.currentTimeMillis());
                if(type.equals("pc")){
                    token.setExpTime(System.currentTimeMillis()+2*60*60*1000);
                    stringRedisTemplateUtil.setKeyTime(sb.toString(), JSON.toJSONString(itripUser),60*2);
                }else{
                    token.setExpTime(Long.MAX_VALUE);
                    stringRedisTemplateUtil.setKey(sb.toString(), JSON.toJSONString(itripUser));
                }
                return dtoUtil.getDto("6000","登陆成功",token,"true",null);
            }else {
                return dtoUtil.getDto("6001","账号密码错误或者还未激活",null,"false",null);
            }
        }catch (Exception e){
            return dtoUtil.getDto("4002","异常",null,"flase",e);
        }

    }

    /**
     * 注册方法
     * @param itripUser 注册信息
     * @return
     */
    @Override
    public Dto register(ItripUser itripUser) {
        try {
            int num = itripUserMapper.insert(itripUser);
            if (num > 0) {
                String code = itripUser.getUserCode();
                //判断code不是邮箱就是手机
                Pattern pattern = Pattern.compile("^[A-Za-z0-9\\u4e00-\\u9fa5]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$");
                Matcher matcher1 = pattern.matcher(code);
                boolean flag = matcher1.matches();
                if (flag) {
                    // 2 生成一个验证码 保存到redis
                    String code1 = UUID.randomUUID().toString().replace("-", "").substring(16);
                    stringRedisTemplateUtil.setKeyTime(itripUser.getUserCode(), code1, 5);
                    //3  发送邮件给客户
                    mailMessage.setText("欢迎注册,您的验证码是" + code1);
                    mailMessage.setSentDate(new Date());
                    mailMessage.setTo(itripUser.getUserCode());
                    mailSender.send(mailMessage);
                    //4 响应用户 结果
                    return dtoUtil.getDto("5000", "注册成功,等待激活", null, "true", null);
                } else {
                    String yzm = mobileUtil.getcode(itripUser.getUserCode());
                    stringRedisTemplateUtil.setKeyTime(itripUser.getUserCode(), yzm, 5);
                    return dtoUtil.getDto("5000", "注册成功,等待激活", null, "true", null);
                }
            } else {
                return dtoUtil.getDto("5002", "数据库添加异常", null, "false", null);
            }
        }
            catch (Exception e){
            return dtoUtil.getDto("5001","异常",null,"false",e);
        }
    }

    /**
     * 用户名验证
     * @param code  用户名
     * @return
     */
    @Override
    public Dto ajaxcode(String code) {
        try {
            ItripUser itripUser= itripUserMapper.selectBycodeandpwd(code,null);
            if (itripUser==null){
                return dtoUtil.getDto("4001","用户名可用",null,"true",null);
            }
            return dtoUtil.getDto("4001","用户已存在",null,"false",null);
        }catch (Exception e){
            return dtoUtil.getDto("4002","异常",null,"flase",e);
        }
    }

    /**
     * 用户激活方法
     * @param user
     * @param code
     * @return
     */
    @Override
    public Dto activationuser(String user, String code) {
        try {
            String jihuoma= stringRedisTemplateUtil.getKey(user);
            if (jihuoma!=null&&jihuoma.equals(code)){
                itripUserMapper.updateByPrimaryKey(user);
                return dtoUtil.getDto("0","激活成功",null,"true",null);
            }
            return  dtoUtil.getDto("3001","请确认激活码",null,"false",null);
        }catch (Exception e){
            return dtoUtil.getDto("3002","异常",null,"flase",e);
        }
    }

    /**
     * 用户注销方法
     * @param userCode token
     * @return
     */
     @Override
    public Dto logout(String userCode) {
        try {
            boolean bu= stringRedisTemplateUtil.delKey(userCode);
            if(bu){
                return dtoUtil.getDto("2000","","注销成功","true",null);
            }
            return dtoUtil.getDto("2001","退出失败",null,"false",null);
        }catch (Exception e){
            return dtoUtil.getDto("2002","异常",null,"flase",e);
        }
    }

    /**
     * 置换token放法
     * @param tokenid token
     * @return
     */
     @Override
    public  Dto substitution(String tokenid){
        try{
            ItripUser itripUser= JSONObject.parseObject(stringRedisTemplateUtil.getKey(tokenid),ItripUser.class);
            stringRedisTemplateUtil.del(tokenid);
            //  redisUtil.setValueExpire(user.getId()+"_"+user.getUsercode(),user.getUsername(),600L);
            //生成一个token    token:来源-用户ID编码加密-用户ID-生成的时间-6位随机码
            StringBuilder sb=new StringBuilder();
            sb.append("token:"+
                    "pc"+"-"
                    + Md5Util.encode(itripUser.getUserCode())+
                    "-"+itripUser.getId()+new SimpleDateFormat("yyyyyMMddHHmmss").format(new Date())
                    +"-"+UUID.randomUUID().toString().replace("-","").substring(6));;
            Token token=new Token();
            token.setToken(sb.toString());
            token.setGenTime(System.currentTimeMillis());
            token.setExpTime(System.currentTimeMillis()+2*60*60*1000);
            stringRedisTemplateUtil.setKeyTime(sb.toString(), JSON.toJSONString(itripUser),60*2);
            return dtoUtil.getDto("1000","",token,"true",null);
        }catch (Exception e){
            return  dtoUtil.getDto("1001","",null,"false",e);

        }
    }
}
